package goods

import (
	"context"
	"errors"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	v1 "video-api/api/v1"
	"video-api/internal/middleware"
	"video-api/internal/model/out"
	"video-api/internal/service"
)

type GoodsController struct{}

var GoodsHandle = new(GoodsController)

func (s *GoodsController) GetGoodsById(ctx context.Context, req *v1.GoodsInfoReq) (*v1.GoodsRes, error) {
	info := middleware.GetUserInfo(ctx)
	fmt.Println(info)
	g.Log().Info(ctx, "GoodsController-GetGoodsById param ", g.Map{"req": req})
	//获取商品信息
	goods, err := service.GoodsService().GetGoodsInfoById(ctx, &req.GoodsDetail)
	if err != nil {
		g.Log().Error(ctx, "GetGoodsById-GetGoodsInfoById 查询错误: "+err.Error(), g.Map{"goodsId": req.GoodsDetail.GoodsId})
		return nil, err
	}
	if goods == nil {
		g.Log().Error(ctx, "GetGoodsById-GetGoodsInfoById 商品不存在", g.Map{"goodsId": req.GoodsDetail.GoodsId})
		return nil, errors.New("商品不存在")
	}
	if goods.Id == 0 {
		g.Log().Error(ctx, "GetGoodsById 商品未找到", g.Map{"goodsId": req.GoodsDetail.GoodsId})
		return nil, errors.New("商品未找到")
	}

	res := new(v1.GoodsRes)
	// 数据转换
	res.DTO(goods)
	return res, nil
}

func (s *GoodsController) GetGoodsList(ctx context.Context, req *v1.GoodsListReq) (*out.Paging, error) {
	g.Log().Info(ctx, "GoodsController-GetGoodsList param ", g.Map{"req": req})
	if req.DeviceType == "" {
		req.DeviceType = "web"
		//return nil, errors.New("设备类型为空")
	}
	//获取商品信息
	goodsList, count, err := service.GoodsService().GetGoodsList(ctx, &req.GoodsList)
	if err != nil {
		g.Log().Error(ctx, "GetGoodsList-GetGoodsList err: "+err.Error())
		return nil, err
	}
	res := make([]*v1.GoodsRes, len(goodsList))
	for i, goods := range goodsList {
		ele := new(v1.GoodsRes)
		ele.DTO(goods)
		res[i] = ele
	}
	return out.FillPaging(count, req.Page, req.PageSize, res), nil
}
